import { queryEntity } from '../../services/customer/api';

export default {
  namespace: 'customer',

  state: {
    data: [],
    pagination: {
    },
    loading: true,
    operatorLoading: false,
    selectItems: {
    },
    userSelect: [],
  },

  effects: {
    *fetch({ payload }, { call, put, select }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      payload.pageNo = payload.current;
      const response = yield call(queryOrder, payload);
      if (response && response.code == 200 && response.data && response.data.records) {
        response.data.records.map(data => {
          data['key'] = data.order.id
          if (data.orderItemList && data.orderItemList.length > 0) {
            data.orderItemList.map(item => item['key'] = data.order.id + "-" + item.id)
          }
        });
        const r = {
          data: response.data.records,
          pagination: {
            total: response.data.total,
            pageSize: payload.pageSize,
            current: payload.current,
          },
        };
        yield put({
          type: 'save',
          payload: r,
        });
      }
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *fetchSelectItems({ payload }, { call, put }) {
      const response = yield call(queryEntity, payload, payload.service, payload.apiUrl);
      if (response && response.code == 200) {
        response.data.records.map(data => data['key'] = data.id);
        const r = {};
        r[payload.selectName] = response.data.records;
        yield put({
          type: 'saveSelectItems',
          payload: r,
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload.data,
        pagination: action.payload.pagination,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    changeOperatorLoading(state, action) {
      return {
        ...state,
        operatorLoading: action.payload,
      };
    },
    saveSelectItems(state, action) {
      return {
        ...state,
        selectItems: {
          ...state.selectItems,
          ...action.payload,
        },
      }
    },
  },

};
